package com.licheng.filter;

import com.licheng.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

//@WebFilter(urlPatterns = "/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求url
        String url = request.getRequestURL().toString();

        //2.如果请求是login直接放行
        if (url.contains("/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //3.判断是否有token，如果没有直接响应401，否则下一步
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {//这里用这个StringUtils.hasLength是为了剔除字符串为空和字符串中有0个以上空格的情况
            response.setStatus(401);
            return;
        }
        //4.解析token，如果解析失败直接相应401否者放行
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回错误信息");
            response.setStatus(401);
            return;
        }
        //5.放行

        log.info("令牌合法，直接放行");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
